#include "newprojectdialog.h"

NewProjectDialog::NewProjectDialog(QWidget *parent): QDialog(parent)
{
    this->setFixedSize(560, 128);
    this->setWindowTitle(tr("New Project"));

    QVBoxLayout *verticalLayout = new QVBoxLayout(this);

    QHBoxLayout *hLayout2 = new QHBoxLayout();
    nameLabel = new QLabel(this);
    nameLabel->setText(tr("Project Name:    "));

    hLayout2->addWidget(nameLabel);

    nameLineEdit = new QLineEdit(this);
    nameLineEdit->setText("Untitled");

    hLayout2->addWidget(nameLineEdit);

    QGroupBox *groupBox2 = new QGroupBox(this);

    groupBox2->setAutoFillBackground(false);
    groupBox2->setStyleSheet(QString::fromUtf8("QGroupBox {border: 0;}"));
    QHBoxLayout *hLayout3 = new QHBoxLayout(groupBox2);
    CRadioButton = new QRadioButton(groupBox2);
    CRadioButton->setText(tr("C Project"));
    CRadioButton->setChecked(true);

    hLayout3->addWidget(CRadioButton);

    CPPRadioButton = new QRadioButton(groupBox2);
    CPPRadioButton->setText(tr("CPP Project"));

    hLayout3->addWidget(CPPRadioButton);

    hLayout2->addWidget(groupBox2);

    verticalLayout->addLayout(hLayout2);

    QHBoxLayout *hLayout1 = new QHBoxLayout();
    locationLabel = new QLabel(this);
    locationLabel->setText(tr("Project Location:"));

    hLayout1->addWidget(locationLabel);

    locationLineEdit = new QLineEdit(this);
    locationLineEdit->setText(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));

    hLayout1->addWidget(locationLineEdit);

    browseButton = new QPushButton(this);
    browseButton->setText(tr("Browse..."));

    hLayout1->addWidget(browseButton);

    verticalLayout->addLayout(hLayout1);

    okCancelButtonBox = new QDialogButtonBox(this);
    okCancelButtonBox->setStyleSheet(QString::fromUtf8(""));
    okCancelButtonBox->setOrientation(Qt::Orientation::Horizontal);
    okCancelButtonBox->setStandardButtons(QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok);

    connect(browseButton, &QPushButton::clicked, this, &NewProjectDialog::browseButtonClicked);

    connect(okCancelButtonBox, &QDialogButtonBox::accepted, this, &NewProjectDialog::okButtonClicked);
    connect(okCancelButtonBox, &QDialogButtonBox::rejected, this, qOverload<>(&QDialog::reject));

    verticalLayout->addWidget(okCancelButtonBox);
}

void NewProjectDialog::showEvent(QShowEvent *e)
{
    QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    QSettings setting(appDataPath + "/Setting.ini", QSettings::IniFormat);

    CRadioButton->setChecked(setting.value("CRadioButtonChecked", true).toBool());
    CPPRadioButton->setChecked(setting.value("CPPRadioButtonChecked", false).toBool());
    QString documentPath=QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    locationLineEdit->setText(setting.value("locationLineEditText", documentPath).toString());

    //给出初步的项目名
    QString projectName="Untitled";
    for (int i=1; i<1000; i++)
    {
        projectName="Untitled"+QString::number(i);
        QFileInfo info(locationLineEdit->text()+"/"+projectName);
        if (!info.exists()) break;
    }
    nameLineEdit->setText(projectName);
}

void NewProjectDialog::browseButtonClicked()
{
    QString selectedPath = QFileDialog::getExistingDirectory(this, "Select a folder", "");
    if (selectedPath.isEmpty()) return;

    if (!isDirWritable(selectedPath))
    {
        QMessageBox::warning(this, tr("Written Protected"), tr("%1The above folder is written protected!").arg(selectedPath+"\n\n"));
    }
    else
    {
        locationLineEdit->setText(selectedPath);
        //给出初步的项目名
        QString projectName="Untitled";
        for (int i=1; i<1000; i++)
        {
            projectName="Untitled"+QString::number(i);
            QFileInfo info(locationLineEdit->text()+"/"+projectName);
            if (!info.exists()) break;
        }
        nameLineEdit->setText(projectName);
    }
}

void NewProjectDialog::okButtonClicked()
{
    QString dirStr=locationLineEdit->text();
    dirStr=dirStr.trimmed();
    QDir dir(dirStr);
    if (!dir.exists())
    {
        QMessageBox::warning(this, tr("Folder invalid"), tr("%1The above folder does not exist!").arg(dir.absolutePath()+"\n\n"));
        locationLineEdit->setFocus();
        return;
    }

    QString projectPath=nameLineEdit->text();
    projectPath=projectPath.remove('\\');
    projectPath=projectPath.remove('/');
    nameLineEdit->setText(projectPath);
    if (nameLineEdit->text().trimmed().isEmpty())
    {
        QMessageBox::warning(this, tr("Empty Project Name"), tr("Please input a project name!"));
        nameLineEdit->setFocus();
        return;
    }

    QString projectFolder=dir.absolutePath()+"/"+nameLineEdit->text();
    if (QDir(projectFolder).exists())
    {
        QMessageBox::warning(this, tr("Project already exists"), tr("%1The above project already exists!%2Please input a new project name!").arg(nameLineEdit->text()+"\n\n", "\n"));
        nameLineEdit->setFocus();
        return;
    }

    projectPath=nameLineEdit->text();
    projectPath=projectPath.remove('\\');
    projectPath=projectPath.remove('/');
    nameLineEdit->setText(projectPath);

    if (projectPath.contains(" "))
    {
        QMessageBox::warning(this, "Warning!", tr("White spaces are not allowed in project name!"));
        nameLineEdit->setFocus();
        return;
    }

    bool mkdirOK=dir.mkdir(projectPath);
    if (!mkdirOK)
    {
        QMessageBox::warning(this, tr("Creating subfolder failed"), tr("%1Failed to create project folder!%2Project name contains illegal characters!").arg(nameLineEdit->text()+"\n\n", "\n"));
        nameLineEdit->setFocus();
        return;
    }
    else
    {
        QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
        QSettings setting(appDataPath + "/Setting.ini", QSettings::IniFormat);
        setting.setValue("CRadioButtonChecked", CRadioButton->isChecked());
        setting.setValue("CPPRadioButtonChecked", CPPRadioButton->isChecked());
        setting.setValue("locationLineEditText", locationLineEdit->text());

        this->accept();//发射确定信号
    }
}

QString NewProjectDialog::projectPath()
{
    return locationLineEdit->text()+"/"+nameLineEdit->text();
}

bool NewProjectDialog::isCRadioButtonChecked()
{
    return CRadioButton->isChecked();
}

bool NewProjectDialog::isCPPRadioButtonChecked()
{
    return CPPRadioButton->isChecked();
}

bool NewProjectDialog::isDirWritable(const QString& dir)
{
    QTemporaryDir tempDir(QDir::cleanPath(dir)+QDir::separator());
    if (tempDir.isValid())
        return true;
    else
        return false;
}
